package cn.apiManager.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;


public class ImageUploadUtils {

    private String allowSuffix = "jpg,png,gif,jpeg";//允许文件格式
    private long allowSize = 2L;//允许文件大小
     
    public String getAllowSuffix() {
        return allowSuffix;
    }
 
    public void setAllowSuffix(String allowSuffix) {
        this.allowSuffix = allowSuffix;
    }
 
    public long getAllowSize() {
        return allowSize*1024*1024;
    }
 
    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }
    
    public String createFile(MultipartFile file, String path) {
        try {
            if (null != file) {
                
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                int length = getAllowSuffix().indexOf(suffix);
                File userFileDir = new File(path);
                
                if (length == -1) {
                    throw new Exception("请上传允许格式的文件");
                }
                if (file.getSize() > getAllowSize()) {
                    throw new Exception("您上传的文件大小已经超出范围");
                }

                if (file.getSize() > 0) {
                  
                    if (!userFileDir.exists()) {
                        userFileDir.mkdirs();
                    }

                    String image = DateTimeUtils.getCurrentDateToLongString("") + "." + suffix;
                    File f = new File(userFileDir.getAbsoluteFile() + "/" + image);
                    file.transferTo(f);
                    f.createNewFile();

                    return image;
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "";
    }
    
   
}
